package com.zero.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zero.entity.*;
import com.zero.mapper.FamilyMapper;
import com.zero.mapper.FamilyMemberMapper;
import com.zero.mapper.LoanMapper;
import com.zero.util.DateUtils;
import com.zero.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class LoanService {

    @Autowired
    private AssetsDebtService assetsDebtService;

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Transactional
    public Result add(Loan loan, HttpServletRequest request){
        if (loan == null)
            return Result.fail("获取不到添加的信息");

        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到个人信息");

        //获取用户的具体信息
        familyMember  = familyMemberMapper.selectById(familyMember.getId());
        Family family = familyMapper.selectById(familyMember.getFamilyId());


        //借出则资产流出，借入则资产流入
        if (loan.getType() == 0){
            familyMember.setDebt(familyMember.getDebt().add(loan.getMoney()));
            family.setDebt(family.getDebt().add(loan.getMoney()));
        }else{
            familyMember.setAssets(familyMember.getAssets().add(loan.getMoney()));
            family.setAssets(family.getAssets().add(loan.getMoney()));
        }

        familyMemberMapper.update(familyMember);
        familyMapper.update(family);

        loan.setMemberId(familyMember.getId());
        loan.setFamilyId(familyMember.getFamilyId());
        loan.setStatus(0);

        int row = loanMapper.add(loan);
        if (row == 1)
            return Result.ok("添加借贷信息成功");
        return Result.fail("添加借贷信息失败");
    }

    @Transactional
    public Result delete(String ids){
        if (ids == null)
            return Result.fail("获取不到要删除的记录");
        String[] idSet = ids.split(",");
        int row = 0;
        for (String id : idSet) {
            row += loanMapper.delete(Integer.parseInt(id));
        }
        if (row > 0)
            return Result.ok("成功删除"+ row +"条记录");
        return Result.fail("删除失败");
    }

    @Transactional
    public Result update(Loan loan, HttpServletRequest request){
        if (loan == null)
            return Result.fail("获取不到修改的信息");

        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到个人信息");
        familyMember = familyMemberMapper.selectById(familyMember.getId());
        Family family = familyMapper.selectById(familyMember.getFamilyId());


        Loan oldLoan = loanMapper.selectById(loan.getId());

        //借出则资产流出，借入则资产流入
        if (loan.getType() == 0){
            familyMember.setDebt(familyMember.getDebt().subtract(oldLoan.getMoney()).add(loan.getMoney()));
            family.setDebt(family.getDebt().subtract(oldLoan.getMoney()).add(loan.getMoney()));
        }else{
            familyMember.setAssets(familyMember.getAssets().subtract(oldLoan.getMoney()).add(loan.getMoney()));
            family.setAssets(family.getAssets().subtract(oldLoan.getMoney()).add(loan.getMoney()));
        }
        familyMemberMapper.update(familyMember);
        familyMapper.update(family);

        int row = loanMapper.update(loan);
        if (row == 1)
            return Result.ok("修改借贷信息成功");
        return Result.fail("修改借贷信息失败");
    }

    public Result select(Condition condition, HttpServletRequest request){
        if (condition == null)
            return Result.fail("获取不到具体的查询信息");

        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");
        familyMember = familyMemberMapper.selectById(familyMember.getId());

        //设置分页查询信息
        condition.setFamilyId(familyMember.getFamilyId());
        if (condition.getPage() != null){
            if (condition .getLimit() != null)
                PageHelper.startPage(condition.getPage(), condition.getLimit());
            else
                PageHelper.startPage(condition.getPage(), 10);
        }else{
            PageHelper.startPage(1, 10);
        }

        List<Loan> loans = loanMapper.selectByCondition(condition);
        for (Loan temp : loans) {
            temp.setFamilyMember(familyMemberMapper.selectById(temp.getMemberId()));
            if (temp.getMemberId() == familyMember.getId())
                temp.setFlag(0);
            else
                temp.setFlag(1);
        }

        PageInfo pageInfo = new PageInfo(loans);
        return Result.ok(loans, pageInfo.getTotal());
    }

    /**
     * 清算借贷
     * @param map
     * @param request
     * @return
     */
    @Transactional
    public Result retrieveLoan(Map map, HttpServletRequest request) {
        if(map == null || !map.containsKey("id") || !map.containsKey("money"))
            return Result.fail("获取不到借贷的回收信息");

        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");

        BigDecimal money = new BigDecimal(map.get("money") + "");

        //获取用户信息
        familyMember = familyMemberMapper.selectById(familyMember.getId());
        //获取家庭信息
        Family family = familyMapper.selectById(familyMember.getFamilyId());


        Loan temp = loanMapper.selectById((Integer) map.get("id"));
        if (temp.getType() == 0){
            //修改家庭资产流入
            BigDecimal assets = family.getAssets().add(money) ;
            family.setAssets(assets);
            familyMapper.update(family);

            //修改个人资产流入
            familyMember.setAssets(familyMember.getAssets().add(money));
            familyMemberMapper.update(familyMember);

        }else{
            //修改家庭资产流出
            family.setDebt(family.getDebt().add(money));
            familyMapper.update(family);

            //修改个人资产流出
            familyMember.setDebt(familyMember.getDebt().add(money));
            familyMemberMapper.update(familyMember);

        }


        //标志投资已回收
        Loan loan = new Loan();
        loan.setRMoney(money);
        loan.setStatus(1);
        loan.setId((Integer)map.get("id"));
        loan.setEndDate(new Date());
        loanMapper.update(loan);

        return Result.ok("已清算");
    }

    public List<Loan> getMemberTodayData(Integer memberId){
        if (memberId == null)
            return null;
        Loan loanParam = new Loan();
        loanParam.setMemberId(memberId);
        loanParam.setStartDate(DateUtils.getToday());
        List<Loan> result = loanMapper.select(loanParam);
        return result;
    }

    public List<Loan> getFamilyTodayData(Integer familyId){
        if (familyId == null)
            return null;
        Loan loanParam = new Loan();
        loanParam.setFamilyId(familyId);
        loanParam.setStartDate(DateUtils.getToday());
        List<Loan> result = loanMapper.select(loanParam);
        return result;
    }
}
